import { AppDataSource } from "@/config/database";
import { CustomerStoredValueCard } from "@/entities/basis/customer-stored-value-card.entity";
import { Customer } from "@/entities/basis/customer.entity";
import { ErrorHandler } from "@/middlewares/error.middleware";
import { Context } from "koa";

/** 获取指定客户的会员卡列表 */
export async function getCustomerStoredValueCards(ctx: Context) {
    const { customerId } = ctx.params;

    if (!customerId) {
        throw new ErrorHandler('客户ID不能为空', 400);
    }

    try {
        // 首先检查客户是否存在
        const customerRepository = AppDataSource.getRepository(Customer);
        const customer = await customerRepository.findOne({
            where: {
                id: customerId,
                deletedAt: null as any
            }
        });

        if (!customer) {
            throw new ErrorHandler('客户不存在', 404);
        }

        // 查询该客户的所有会员卡（只返回余额大于0的）
        const cardRepository = AppDataSource.getRepository(CustomerStoredValueCard);
        const cards = await cardRepository.createQueryBuilder('card')
            .where('card.customerId = :customerId', { customerId })
            .andWhere('card.deletedAt IS NULL')
            .andWhere('card.currentBalance > 0')
            .orderBy('card.createdAt', 'DESC')
            .getMany();

        // 处理返回数据
        const formattedCards = cards.map(card => ({
            ...card,
            // 计算卡片状态
            rechargeAmount: Number(card.rechargeAmount),
            giftAmount: Number(card.giftAmount),
            currentBalance: Number(card.currentBalance),
            giftPoints: Number(card.giftPoints),
            status: getCardStatus(card.validFrom, card.validTo, Number(card.currentBalance))
        }));

        // 计算统计信息
        const totalBalance = formattedCards.reduce((sum, card) => sum + card.currentBalance, 0);
        const totalGiftPoints = formattedCards.reduce((sum, card) => sum + card.giftPoints, 0);
        const activeCards = formattedCards.filter(card => card.status === 'active').length;

        ctx.status = 200;   
        ctx.body = {
            customer,
            cards: formattedCards,
            statistics: {
                totalCards: formattedCards.length,
                activeCards,
                totalBalance,
                totalGiftPoints
            }
        }

    } catch (error) {
        console.error('获取客户会员卡列表失败:', error);
        if (error instanceof ErrorHandler) {
            throw error;
        }
        throw new ErrorHandler('获取客户会员卡列表失败', 500);
    }
}

/** 获取卡片状态 */
function getCardStatus(validFrom?: Date, validTo?: Date, currentBalance?: number): string {
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

    // 如果余额为0，返回已用完
    if (currentBalance === 0) {
        return 'exhausted'; // 已用完
    }

    // 如果没有设置有效期，返回正常
    if (!validFrom && !validTo) {
        return 'active'; // 正常
    }

    // 检查是否在有效期内
    if (validFrom && today < new Date(validFrom)) {
        return 'inactive'; // 未生效
    }

    if (validTo && today > new Date(validTo)) {
        return 'expired'; // 已过期
    }

    return 'active'; // 正常
} 